﻿using System.Globalization;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using StockholmsStad.Windows.UI.Infrastructure;
using StockholmsStad.Windows.UI.Modules.Minister.Interfaces;
using StockholmsStad.Windows.UI.Modules.Minister.Models;
using StockholmsStad.Windows.UI.Modules.Minister.Presenters;
using StockholmsStad.Windows.UI.Modules.Minister.Views;

namespace StockholmsStad.Windows.UI.Modules.Minister.Controllers
{
    public class MinisterController : IMinisterController
    {
        private readonly IUnityContainer container;
        private readonly IRegionManager regionManager;
        private readonly IMinisterService ministerService;

        public MinisterController(IUnityContainer container, IRegionManager regionManager, IMinisterService ministerService)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.ministerService = ministerService;
        }

        public virtual void OnMinisterSelected(MinisterPresentationModel minister)
        {
            if (regionManager.Regions.ContainsRegionWithName(RegionNames.DetailsRegion)
                && minister.MinisterId.HasValue)
            {
                var detailsRegion = regionManager.Regions[RegionNames.DetailsRegion];

                var existingView =
                    detailsRegion.GetView(minister.MinisterId.Value.ToString(CultureInfo.InvariantCulture));
                minister.MinisterServiceList = ministerService.GetTimeBlocks(minister.MinisterId.Value);

                if (existingView == null)
                {
                    var detailsPresenter = container.Resolve<IMinisterDetailsPresenter>();
                    detailsPresenter.SetSelectedMinister(minister);

                    detailsRegion.Add(detailsPresenter.View,
                                      minister.MinisterId.Value.ToString(CultureInfo.InvariantCulture), true);
                    detailsRegion.Activate(detailsPresenter.View);
                }
                else
                {
                    var detailsPresenter = container.Resolve<MinisterDetailsPresenter>();
                    detailsPresenter.SetSelectedMinister(minister);

                    var exist = existingView as MinisterDetailsView;
                    if (exist != null) exist.Model = minister;
                    detailsRegion.Activate(exist);
                }
            }
        }
    }
}
